/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.web;

import cz.muni.fi.pa165.portalnahouby.api.dto.PickerDTO;
import java.lang.reflect.Method;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ActionResolver;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.controller.StripesFilter;

/**
 *
 * @author Lukas Marica
 */
@Intercepts(LifecycleStage.HandlerResolution)
public class SecurityInterceptor implements Interceptor {

	@Override
	public Resolution intercept(ExecutionContext ctx) throws Exception {
		if (ctx.getActionBean().getClass().isAnnotationPresent(DoesNotRequireLogin.class)) {
			return ctx.proceed();
		}
		ActionResolver resolver = StripesFilter.getConfiguration().getActionResolver();
		ActionBeanContext beanContext = ctx.getActionBeanContext();
		Class beanClass = resolver.getActionBean(beanContext).getClass();
		String eventName = resolver.getEventName(beanClass, beanContext);
		Method handler;
		if (eventName != null) {
			handler = resolver.getHandler(beanClass, eventName);
		} else {
			handler = resolver.getDefaultHandler(beanClass);
		}
		if (isLoggedIn(beanContext)) {
			if (handler == null || ! handler.isAnnotationPresent(RequiresAdmin.class) || isLoggedInAdmin(beanContext)) {
				return ctx.proceed();
			} else {
				return new RedirectResolution("/not_enough_rights.jsp");
			}
		} else {
			return new RedirectResolution("/security/login");
		}
	}

	protected boolean isLoggedIn(ActionBeanContext ctx) {
		Boolean loggedIn = (Boolean) ctx.getRequest().getSession().getAttribute("loggedIn");
		return (loggedIn != null && loggedIn);
	}

	protected boolean isLoggedInAdmin(ActionBeanContext ctx) {
		Boolean loggedIn = (Boolean) ctx.getRequest().getSession().getAttribute("loggedIn");
		PickerDTO loggedUser = (PickerDTO) ctx.getRequest().getSession().getAttribute("loggedUser");
		return (loggedIn != null && loggedIn && loggedUser != null && loggedUser.getIsAdmin());
	}
}
